package com.dtflys.easyel.runtime.eval;

import com.dtflys.easyel.ast.ASTNewInstance;
import com.dtflys.easyel.ast.ASTType;
import com.dtflys.easyel.exception.EasyElAmbiguousMethodsException;
import com.dtflys.easyel.exception.EasyElConstructorException;
import com.dtflys.easyel.exception.EasyElEvalException;
import com.dtflys.easyel.runtime.EasyElRuntimeContext;
import com.dtflys.easyel.utils.MetaHelper;

import java.lang.reflect.InvocationTargetException;


/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class NewInstanceEvaluator {

    public Object evaluate(EasyElRuntimeContext context, ASTNewInstance newInstance, Object[] arguments) {
        ASTType type = newInstance.getType();
        try {
            return MetaHelper.newInstance(type.getClazz(), arguments);
        } catch (InvocationTargetException e) {
            throw new EasyElEvalException(context, newInstance, e.getMessage());
        } catch (EasyElAmbiguousMethodsException e) {
            throw new EasyElEvalException(context, newInstance, e.getMessage());
        } catch (EasyElConstructorException e) {
            throw new EasyElEvalException(context, newInstance, e.getMessage());
        } catch (InstantiationException e) {
            throw new EasyElEvalException(context, newInstance, e.getMessage());
        } catch (IllegalAccessException e) {
            throw new EasyElEvalException(context, newInstance, e.getMessage());
        }
    }
}
